package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备Service业务层处理
 * 
 * @author ZTtv
 * @date 2025-08-29
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备
     * 
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备列表
     * 
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     * 
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        UpdateDeviceRequest request = new UpdateDeviceRequest();
            request.setDeviceId(device.getIotId());
            UpdateDevice body = new UpdateDevice();
            body.setDeviceName(device.getDeviceName());
            request.setBody(body);
        try {
             client.updateDevice(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     * 
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     * 
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void syncProductList() {
        // 请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        // 设置条数
        listProductsRequest.setLimit(50);
        // 发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        // 存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));


    }

    @Override
    public List<ProductVo> allProduct() {
        String productList = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if(StringUtils.isEmpty(productList)){
            return List.of();
        }
      return JSONUtil.toList(productList, ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto deviceDto) {
        long count = count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()));
        if(count > 0){
            throw new BaseException("设备名称已存在,请重新输入");
        }
         count = count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()));
        if(count > 0){
            throw new BaseException("设备标识码已存在,请重新输入");
        }
        if(deviceDto.getPhysicalLocationType()==null){
            deviceDto.setPhysicalLocationType(-1);
        }
         count = count(Wrappers.<Device>lambdaQuery().eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                 .eq(Device::getLocationType, deviceDto.getLocationType())
                 .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType()
                 ).eq(Device::getProductKey, deviceDto.getProductKey()));
        if(count > 0){
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        body.withProductId(deviceDto.getProductKey());
        AuthInfo authInfo= new AuthInfo();
        String secret= UUID.randomUUID().toString().replace("-","");
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        request.setBody(body);
        AddDeviceResponse response;
        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，同步失败");
        }
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        save(device);


    }

    @Override
    public DeviceDetailVo selectDeviceDetail(String iotId) {
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if(ObjectUtil.isEmpty(device)){
            return null;
        }
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查询设备详情，同步失败");
        }
        deviceDetailVo.setDeviceStatus(response.getStatus());
       String activeTime=response.getActiveTime();
       if(StringUtils.isNotEmpty(activeTime)){
           LocalDateTime parse = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
           deviceDetailVo.setActiveTime(DateTimeZoneConverter.utcToShanghai( parse));
       }
       return deviceDetailVo;
    }

    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response;
        try {
            response = client.showDeviceShadow(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查询设备影子，同步失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if(ObjectUtil.isEmpty( shadow)){
            return AjaxResult.success(Collections.emptyList());
        }
        // 获取上报数据的reported （参考返回的json数据）
        DeviceShadowProperties reported = shadow.get(0).getReported();
        // 把数据转换为JSONObject(map)，方便处理
        JSONObject jsonObject = JSONUtil.parseObj(reported.getProperties());
        // 遍历数据，封装到list中
        List<Map<String,Object>>  list = new ArrayList<>();
        // 事件上报时间
        String eventTimeStr = reported.getEventTime();
        // 把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);

        // k:属性标识，v:属性值
        jsonObject.forEach((k,v) -> {
            Map<String,Object> map = new HashMap<>();
            map.put("functionId", k);
            map.put("value", v);
            map.put("eventTime", eventTime);
            list.add(map);
        });

        // 数据返回
        return AjaxResult.success(list);
    }

    @Override
    public void deleteDevice(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 删除设备，同步失败");
        }
        deviceMapper.deleteDeviceByIotId(iotId);
    }

    @Override
    public AjaxResult queryProductByProductKey(String productKey) {
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("产品标识码不能为空");
        }
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response;
        try {
            response = client.showProduct(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (ObjectUtil.isEmpty(serviceCapabilities)) {
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(serviceCapabilities);
    }
}
